package com.mtw.bbs.auth.config;



import com.mtw.bbs.auth.utils.JwtTokenUtil;
import com.mtw.bbs.common.core.constant.AuthConstant;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * token过滤器
 */
@Slf4j
@Component
public class JwtBaseRequestFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private static final List<String> IGNORE_URL = new ArrayList<>(16);
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    static {
        IGNORE_URL.add("/login/**");
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {

        //  //如果是options请求直接放过
        if(request.getMethod().matches(HttpMethod.OPTIONS.name())){
            filterChain.doFilter(request, response);
        }
        String path = request.getRequestURI();
        if (isIgnore(path)) {
            filterChain.doFilter(request, response);
        } else {
            String REFRESH_URL = "/refresh";
            String token = antPathMatcher.match(REFRESH_URL, path)?getJwtRefreshToken(request):getJwtServiceToken(request);
            if ("ignore".equals(token)){
                filterChain.doFilter(request, response);
            }else {
                try {
                    if (token != null && jwtTokenUtil.validateJwtToken(token)) {
                        filterChain.doFilter(request, response);
                    }
                } catch (Exception e) {
                    returnNoAuth(response, e.getMessage());
                }
            }

        }

    }


    /**
     * url是否为忽略
     */
    private boolean isIgnore(String path) {
        return IGNORE_URL.stream().anyMatch(pattern -> antPathMatcher.match(pattern, path));
    }


    /**
     * 自定义返回无权限
     */
    private void returnNoAuth(HttpServletResponse response, String msg) {

        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = response.getWriter()) {
            out.print(StringUtils.isNotBlank(msg) ? msg : "无访问权限");
        } catch (IOException e) {
            log.error("sendResponse error：", e);
        }
    }


    /**
     * 从请求头获取refresh token
     */
    private String getJwtRefreshToken(HttpServletRequest request) {
        // 获取token
        return request.getHeader(AuthConstant.REFRESH_TOKEN_HEADER);
    }


    /**
     * 从请求头获取token
     */
    private String getJwtServiceToken(HttpServletRequest request) {
        // 获取token
        return request.getHeader(AuthConstant.SERVICE_AUTH_KEY);
    }
}



